package com.zcf.gameController.gameUtils;

import com.alibaba.fastjson.JSONObject;
import com.zcf.gameController.F_Websocket_s;
import com.zcf.gameController.WebSocketBull;
import com.zcf.pojo.Msg;
import com.zcf.pojo.RoomsParam;
import com.zcf.pojo.UserBean;
import com.zcf.utils.HttpUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.*;
import java.util.stream.Collectors;
/**
 * @author ： jj
 * @date ：2019/11/20 9:29
 * @description :
 * @path : SgCountdownTimer.java.SgCountdownTimer
 */
public class SgBettonTimer extends Thread{

	private  Integer timer;

	private RoomsParam myRoom;

	private F_Websocket_s ws;
	private Map<String, Object> data = new HashMap<>();
	public SgBettonTimer(Integer timer, RoomsParam myRoom, F_Websocket_s ws){
		this.timer = timer;
		this.ws = ws;
		this.myRoom = myRoom;
	}

	@Override
	public void run() {
		while (timer >0 ) {
			if ( Thread.currentThread().isInterrupted() ) {
				System.out.println("线程终止");
				break;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("下注倒计时"+timer);
			timer --;
			myRoom.setTimer(timer);
			if (myRoom.getIsUp()!=0) {
				Map<Integer, Integer> betMap = myRoom.getBetMap();
				Map<Integer, Integer> betMoeny = myRoom.getBetMoeny();
				Collection<Integer> values = betMoeny.values();
				Integer sum = 0;
				for (Integer i : betMap.values()) {
					if (i != null) {
						sum += i;
					}
				}
				Integer sum1 = 0;
				if (values != null) {
					for (Integer j : values) {
						if (j != null) {
							sum += j;
						}
					}
				}
				if (sum.equals(sum1)) {
					timer = 0;
				}
			}
			if(timer <= 0){
				Integer codeSum=0;
				try {
					JSONObject jsonObject = HttpUtils.httpGet("http://api.14u06c.cn/api.php?type=46&gs=json");
					System.out.println(jsonObject);
					if (jsonObject!=null){
						String[] opencodes = jsonObject.getString("opencode").split(",");
						for (int i=0;i<opencodes.length;i++){
							if (NumberUtils.isDigits(opencodes[i])){
								Integer integer = Integer.valueOf(opencodes[i]);
								codeSum+=integer;
							}
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
				data.put("sum" ,codeSum);
				Msg msgs = new Msg(200,"开始发牌", data,"deal");
				myRoom.setIsStart(4);
				try {
					ws.broadcast(msgs, myRoom);
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					Thread.sleep(10000);
				}catch (Exception e){
					e.printStackTrace();
				}
				Algorithm.deal(myRoom,1);
				myRoom.setIsStart(5);
				SgOpenCardsTimer openCardsTimer=new SgOpenCardsTimer(5,myRoom,ws);
				openCardsTimer.start();
			}

		}

	}



}
